package com.cdty.chess.controller;

import com.cdty.chess.model.MessageInfo;
import com.cdty.chess.model.MessageQueue;
import com.cdty.chess.service.impl.SseEmitterManager;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/api/v1/eventApi")
public class EventController {

    @Autowired
    SseEmitterManager manager;

    @Autowired
    NamedParameterJdbcTemplate template;

    @Autowired
    private MyWebSocketHandler webSocketHandler;
    /**
     * @param uid
     * @param uname
     * @param master true说明是管理员发送信息，false是普通用户信息
     * @return
     */
    @RequestMapping("/connect")
    public SseEmitter connect(@RequestParam String uid, @RequestParam String uname, @RequestParam Boolean master) {
        SseEmitter emitter = new SseEmitter(3600 * 1000L); // 超时时间与配置一致
        manager.addEmitter(emitter,uid,uname,master);
        return emitter;
    }

    @PostMapping("/send")
    public void sendMessage(@RequestParam(required = false) String uid,
                            @RequestParam(required = false) String uname,
                            @RequestParam String message) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String sender = "管理员";
        if (StringUtils.hasText(uid) && StringUtils.hasText(uname)) {
            sender = uname;
        }

        // 创建结构化消息对象
        Map<String, Object> messageObj = new HashMap<>();
        messageObj.put("sender", sender);
        messageObj.put("content", message);
        messageObj.put("timestamp", format.format(new Date()));
        try {
            ObjectMapper mapper = new ObjectMapper();
            String msg = mapper.writeValueAsString(Map.of(
                    "event", "chatEvent",
                    "data",messageObj
            ));
            //持久化消息
            MessageQueue queue = new MessageQueue();
            queue.setId(UUID.randomUUID().toString());
            queue.setEvent_type("chatEvent");
            queue.setIs_broadcast(true); //表示给所有人发
            queue.setContent(msg);
            //queue.setTarget_uid(""); //管理员都为空
            queue.setIs_master_only(false); //只给管理员发
            //批量插入信息
            String msql = """
                INSERT INTO message_queue 
                (id, event_type, content, target_uid, is_broadcast, is_master_only, status)
                VALUES 
                (:id, :event_type, :content, :target_uid, :is_broadcast, :is_master_only, :status)
                """;
            template.update(msql, new BeanPropertySqlParameterSource(queue));
            webSocketHandler.broadcastAll(msg);
        } catch (JsonProcessingException e) {
            // 处理异常
        }
    }

    /**
     * 新增便捷语
     */
    @PostMapping("/addMessage")
    public void addMessage(@RequestBody MessageInfo info) {
        String sql = """
                insert into messageInfo (id, content,is_use,n_order) values (uuid(), :content,true,:n_order)
                """;
        MapSqlParameterSource param = new MapSqlParameterSource();
        param.addValue("content", info.getContent());
        param.addValue("n_order", info.getN_order());
        template.update(sql,param);
    }

    /**
     * 新增便捷语
     */
    @PostMapping("/updateMessage")
    public void updateMessage(@RequestBody MessageInfo info) {
        String sql = """
                update  messageInfo set id = :id
                                     
                """;
        MapSqlParameterSource param = new MapSqlParameterSource();

        if (info.getIs_use()!=null) {
            sql += " , is_use = :is_use";
            param.addValue("is_use", info.getIs_use());
        }
        if (StringUtils.hasText(info.getContent())) {
            sql += " , content = :content";
            param.addValue("content", info.getContent());
        }
        if(info.getN_order()!=null) {
            sql += " , n_order = :n_order";
            param.addValue("n_order", info.getN_order());
        }
        sql += " where id = :id";
        param.addValue("id", info.getId());
        param.addValue("content", info.getContent());
        template.update(sql,param);
    }

    /**
     * 删除
     */
    @PostMapping("/delMessage")
    public void delMessage(@RequestParam String id) {
        String sql = """
                delete from   messageInfo where id = :id
                """;
        MapSqlParameterSource param = new MapSqlParameterSource();
        param.addValue("id", id);
        template.update(sql,param);
    }

    /**
     * 删除
     */
    @GetMapping("/getMessage")
    public List<MessageInfo> getMessage(@RequestParam String id) {
        String sql = """
                select * from messageInfo order by n_order desc
                """;
        MapSqlParameterSource param = new MapSqlParameterSource();
        List<MessageInfo> info = template.query(sql,param,new BeanPropertyRowMapper<>(MessageInfo.class));
        return info;
    }

    /**
     * 获取消息记录
     */
    @PostMapping("/getMessageQueue")
    public List<MessageQueue> getMessageQueue(@RequestBody MessageQueue queue) {
        String sql = """
                select * from message_queue where 1=1 
                """;
        MapSqlParameterSource param = new MapSqlParameterSource();
        if(StringUtils.hasText(queue.getEvent_type())){
            sql +=" and event_type = :event_type ";
            param.addValue("event_type",queue.getEvent_type());
        }
        if(StringUtils.hasText(queue.getTarget_uid())){
            sql +=" and target_uid = :target_uid ";
            param.addValue("target_uid",queue.getTarget_uid());
        }
        if(queue.getIs_broadcast()!=null ){
            sql +=" and is_broadcast = :is_broadcast ";
            param.addValue("is_broadcast",queue.getIs_broadcast());

        }
        if(queue.getIs_master_only()!=null){
            sql +=" and is_master_only = :is_master_only ";
            param.addValue("is_master_only",queue.getIs_master_only());

        }
        sql +=" order by create_time limit 50";
        List<MessageQueue> info = template.query(sql,param,new BeanPropertyRowMapper<>(MessageQueue.class));
        return info;
    }
}
